package com.sunyard.pcc.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;


import javax.servlet.http.HttpServletRequest;

/**
 * @Author: Hewei
 * @Description: http相关工具方法
 * @Date: Created in 9:40 2018/3/15
 */
@Slf4j
public class HttpUtil {

    /**
     * 根据httpRequest获取Ip地址
     * @param request
     */
    public static String getIPByRequest(HttpServletRequest request){
        String ip = null;
        ip = request.getHeader("x-forwarded-for");
        if (!checkIp(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (!checkIp(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (!checkIp(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (!checkIp(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (!checkIp(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * ip地址检查
     * @param ip
     * @return
     */
    private static boolean checkIp(String ip){
        if (StringUtils.isEmpty(ip)
                || "unknown".equalsIgnoreCase(ip)
                || ip.split(".").length != 4){
            return false;
        }

        return true;
    }

}
